package com.zaoshui.hudada.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zaoshui.hudada.common.ErrorCode;
import com.zaoshui.hudada.constant.CommonConstant;
import com.zaoshui.hudada.exception.BusinessException;
import com.zaoshui.hudada.exception.ThrowUtils;
import com.zaoshui.hudada.model.dto.scoringresult.ScoringResultQueryRequest;
import com.zaoshui.hudada.model.entity.App;
import com.zaoshui.hudada.model.entity.ScoringResult;
import com.zaoshui.hudada.model.entity.User;
import com.zaoshui.hudada.model.vo.ScoringResultVO;
import com.zaoshui.hudada.model.vo.UserVO;
import com.zaoshui.hudada.service.AppService;
import com.zaoshui.hudada.service.ScoringResultService;
import com.zaoshui.hudada.mapper.ScoringResultMapper;
import com.zaoshui.hudada.service.UserService;
import com.zaoshui.hudada.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author lihai
* @description 针对表【scoring_result(评分结果)】的数据库操作Service实现
* @createDate 2024-05-24 16:57:01
*/
@Service
public class ScoringResultServiceImpl extends ServiceImpl<ScoringResultMapper, ScoringResult>
    implements ScoringResultService{
    @Resource
    private UserService userService;

    @Resource
    private AppService appService;


    /*
     * 校验参数
     * */
    @Override
    public void validScoringResult(ScoringResult scoringResult, boolean add) {
        if (scoringResult == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String resultName = scoringResult.getResultName();
        String resultDesc = scoringResult.getResultDesc();
        Long appId = scoringResult.getAppId();


        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(resultName), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(resultName) && resultName.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "结果名称过长");
        }
        if (StringUtils.isNotBlank(resultDesc) && resultDesc.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "结果描述过长");
        }
        App app = appService.getById(appId);
        ThrowUtils.throwIf(app == null, ErrorCode.PARAMS_ERROR, "应用不存在");

    }

    /**
     * 获取查询包装类
     *
     * @param scoringResultQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<ScoringResult> getQueryWrapper(ScoringResultQueryRequest scoringResultQueryRequest) {
        QueryWrapper<ScoringResult> queryWrapper = new QueryWrapper<>();
        if (scoringResultQueryRequest == null) {
            return queryWrapper;
        }
        Long id = scoringResultQueryRequest.getId();
        String resultName = scoringResultQueryRequest.getResultName();
        String resultDesc = scoringResultQueryRequest.getResultDesc();
        Integer resultScoreRange = scoringResultQueryRequest.getResultScoreRange();
        Long appId = scoringResultQueryRequest.getAppId();
        Long userId = scoringResultQueryRequest.getUserId();
        String sortField = scoringResultQueryRequest.getSortField();
        String sortOrder = scoringResultQueryRequest.getSortOrder();

        //模糊查询
        queryWrapper.like(StringUtils.isNotBlank(resultName), "resultName", resultName);
        queryWrapper.like(StringUtils.isNotBlank(resultDesc), "resultDesc", resultDesc);

        //精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(appId), "appId", appId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(resultScoreRange), "resultScoreRange", resultScoreRange);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


    @Override
    public ScoringResultVO getScoringResultVO(ScoringResult scoringResult, HttpServletRequest request) {
        ScoringResultVO scoringResultVO = ScoringResultVO.objToVo(scoringResult);
        long scoringResultId = scoringResult.getId();
        // 1. 关联查询用户信息
        Long userId = scoringResult.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        scoringResultVO.setUser(userVO);
        return scoringResultVO;
    }

    @Override
    public Page<ScoringResultVO> getScoringResultVOPage(Page<ScoringResult> scoringResultPage, HttpServletRequest request) {
        List<ScoringResult> scoringResultList = scoringResultPage.getRecords();
        Page<ScoringResultVO> scoringResultVOPage = new Page<>(scoringResultPage.getCurrent(), scoringResultPage.getSize(), scoringResultPage.getTotal());
        if (CollUtil.isEmpty(scoringResultList)) {
            return scoringResultVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = scoringResultList.stream().map(ScoringResult::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<ScoringResultVO> scoringResultVOList = scoringResultList.stream().map(scoringResult -> {
            ScoringResultVO scoringResultVO = ScoringResultVO.objToVo(scoringResult);
            Long userId = scoringResult.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            scoringResultVO.setUser(userService.getUserVO(user));

            return scoringResultVO;
        }).collect(Collectors.toList());
        scoringResultVOPage.setRecords(scoringResultVOList);
        return scoringResultVOPage;
    }
}




